'use strict'

/**
 * @description 自动更新功能模块
 */

import { autoUpdater } from 'electron-updater'
import { dialog, ipcMain } from 'electron'

/**
 * @description 自动更新事件
 */
export default function updateHandle(win, url, sendupdateStatus) {
  let hasAuto = true // 是否存在安装包
  let autoInstall = true
  autoUpdater.autoDownload = false
  autoUpdater.setFeedURL(url)

  autoUpdater.on('error', (error) => {
    console.log("error")
    console.log(error)
    sendupdateStatus(error, {})
  })

  // 检查是否有最新的更新包
  autoUpdater.on('checking-for-update', () => {
    console.log('checking-for-update')
    sendupdateStatus('checking', {})
  })

  /* =====================用户点击更新===========================*/

  // 需不需要更新
  autoUpdater.on('update-available', (info) => {
    console.log('update-available')
    sendupdateStatus('update-available', {})
    autoUpdater.downloadUpdate()
    sendupdateStatus('downloading', {})
  })

  autoUpdater.on('update-not-available', (info) => {
    console.log('update-not-available')
    if (!hasAuto) {
      sendupdateStatus('notAvailable', {})
    }
  })

  // 更新下载进度事件
  autoUpdater.on('download-progress', (progressObj) => {
    console.log('download-progress')
    autoInstall = false
    sendupdateStatus('download-progress', progressObj)
  })

  autoUpdater.on('update-downloaded', (
    event,
    releaseNotes,
    releaseName,
    releaseDate,
    updateUrl,
    quitAndUpdate
  ) => {
    console.log('本地保存系统最新安装包的地址' + updateUrl)
    console.log('update-downloaded')
    const haha = {
      event,
      releaseNotes,
      releaseName,
      releaseDate,
      quitAndUpdate
    }
    sendupdateStatus('downloaded', haha)
    if (autoInstall) {
      const options = {
        type: 'info',
        title: '更新提醒',
        message: '已经下载最新版本的系统，是否替换？',
        buttons: ['立即替换', '暂不替换'],
        defaultId: 0,
        cancelId: 1
      }
      dialog.showMessageBox(win, options).then(({ response, checkboxChecked }) => {
        if (response === 0) {
          autoUpdater.quitAndInstall()
        }
      })
    }
  })

  ipcMain.on('quitAndInstall', () => {
    console.log('主进程进入quitAndInstall')
    autoUpdater.quitAndInstall()
  })


  autoUpdater.checkForUpdates()

  ipcMain.on('checkForUpdate', (auto) => {
    // 执行自动更新检查
    hasAuto = auto
    autoUpdater.checkForUpdates()
  })
}
